<template>
  <div class="min-h-screen bg-blue-50">
    <!-- 页面头部 -->
    <header class="border-b border-gray-200 relative overflow-hidden py-8 sm:py-12 lg:py-16">
      <!-- 弹幕系统 -->
      <BarrageSystem 
        :stats-data="statsData"
        :custom-barrage-data="questionBarrageData"
        @tag-click="handleTagClick"
      />

      <!-- 主要内容层 -->
      <div class="container mx-auto px-4 py-4 sm:py-6 lg:py-8 relative z-10">
        <div class="text-center">
          <div class="inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-full mb-3 sm:mb-4 shadow-lg">
            <svg class="w-6 h-6 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
            </svg>
          </div>
          <h1 class="text-2xl sm:text-3xl lg:text-4xl font-bold bg-gradient-to-r from-purple-700 via-indigo-600 to-blue-600 bg-clip-text text-transparent">算法题库</h1>
          <p class="text-gray-600 mt-2 text-base sm:text-lg">提升编程技能，备战技术面试</p>
        </div>
      </div>
    </header>

    <!-- 系统公告横幅 -->
    <div class="container mx-auto px-4 py-4">
      <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-2xl p-4 shadow-sm">
        <!-- 加载状态 -->
        <div v-if="announcementsLoading" class="flex items-center space-x-3">
          <div class="w-8 h-8 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full flex items-center justify-center">
            <svg class="w-4 h-4 text-white animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
            </svg>
          </div>
          <div>
            <h3 class="font-semibold text-gray-900">系统公告</h3>
            <p class="text-sm text-gray-600">正在加载公告...</p>
            </div>
            </div>

        <!-- 有公告时显示 -->
        <div v-else-if="announcements.length > 0" class="flex items-center justify-between">
          <div class="flex items-center space-x-3">
            <div class="w-8 h-8 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full flex items-center justify-center">
              <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z"></path>
              </svg>
            </div>
            <div>
              <h3 class="font-semibold text-gray-900">最新公告</h3>
              <p class="text-sm text-gray-600">{{ announcements[0].title }}</p>
            </div>
          </div>
          <button 
            @click="showAllAnnouncements = !showAllAnnouncements"
            class="text-gray-500 hover:text-gray-700 transition-colors"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
            </svg>
            </button>
          </div>

        <!-- 无公告时显示 -->
        <div v-else class="flex items-center space-x-3">
          <div class="w-8 h-8 bg-gradient-to-r from-gray-400 to-gray-500 rounded-full flex items-center justify-center">
            <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z"></path>
            </svg>
          </div>
          <div>
            <h3 class="font-semibold text-gray-900">系统公告</h3>
            <p class="text-sm text-gray-600">暂无公告</p>
          </div>
        </div>
        
        <!-- 展开的公告列表 -->
        <div v-if="showAllAnnouncements && announcements.length > 1" class="mt-4 pt-4 border-t border-blue-200">
          <div v-for="a in announcements.slice(1)" :key="a.id" class="flex items-start space-x-3 py-2">
            <div class="w-2 h-2 rounded-full mt-2" :class="a.priority > 0 ? 'bg-red-500' : 'bg-blue-500'"></div>
            <div class="flex-1">
              <p class="text-sm font-medium text-gray-900">{{ a.title }}</p>
              <p class="text-xs text-gray-500">{{ formatDate(a.created_at) }}</p>
      </div>
        </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 快捷操作和统计信息 -->
      <div class="mb-6 sm:mb-8">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 sm:gap-6">
          <!-- 快捷操作按钮 -->
          <div class="flex flex-wrap gap-2 sm:gap-3 w-full sm:w-auto">
            <Button 
              variant="primary"
              size="md"
              @click="goToRandomQuestion"
            >
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
              </svg>
              随机一题
            </Button>
            <Button 
              variant="primary"
              size="md"
              @click="continueLastPractice"
            >
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h1m4 0h1m-6 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
              继续练习
            </Button>
        </div>

          <!-- 统计信息 -->
          <div class="flex flex-wrap gap-3 items-center">
            <StatsCard 
              label="总题数"
              :value="questionStats.total_questions"
              :icon="DocumentIcon"
              color="blue"
            />
            <StatsCard 
              label="已完成"
              :value="userStats.solved_count"
              :icon="CheckIcon"
              color="green"
            />
            <StatsCard 
              label="连续刷题"
              :value="`${userStats.consecutive_days}天`"
              :icon="ClockIcon"
              color="yellow"
            />
            <StatsCard 
              label="正确率"
              :value="`${Math.round(userStats.acceptance_rate * 100)}%`"
              :icon="ShieldIcon"
              color="purple"
            />
          </div>
        </div>
      </div>

      <!-- 筛选和搜索区域 -->
      <SearchForm 
        v-model="searchFilters"
        @search="handleSearch"
        @filter="handleFilter"
      />

      <!-- 每日一题区域 -->
      <DailyQuestionSection />

      <!-- 加载状态 -->
      <LoadingSpinner v-if="loading" text="加载中..." center />

      <!-- 错误状态 -->
      <ErrorState 
        v-else-if="error"
        :message="error"
        @retry="loadQuestions"
      />

      <!-- 题目列表 -->
      <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-4 sm:gap-6 no-scale-cards">
         <QuestionCard 
           v-for="(question, index) in filteredQuestions" 
           :key="question.id"
           :question="question"
           :index="index"
           :current-page="currentPage"
           :page-size="pageSize"
           @favorite="handleFavorite"
           @unfavorite="handleUnfavorite"
         />
       </div>

      <!-- 分页控件 -->
      <div class="mt-8 bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 border border-white/20">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <p class="text-sm text-gray-700">
              显示第
              <span class="font-medium text-blue-600">{{ (currentPage - 1) * pageSize + 1 }}</span>
              到
              <span class="font-medium text-blue-600">{{ Math.min(currentPage * pageSize, totalQuestions) }}</span>
              条，共
              <span class="font-medium text-blue-600">{{ totalQuestions }}</span>
              条记录
            </p>
          </div>
          <div>
            <nav class="relative z-0 inline-flex rounded-xl shadow-sm -space-x-px">
              <Button
                :disabled="currentPage === 1"
                variant="outline"
                size="sm"
                @click="goToPage(currentPage - 1)"
              >
                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
                上一页
              </Button>
              <Button
                v-for="page in visiblePages"
                :key="page"
                :variant="page === currentPage ? 'primary' : 'outline'"
                size="sm"
                @click="goToPage(page)"
              >
                {{ page }}
              </Button>
              <Button
                :disabled="currentPage === totalPages"
                variant="outline"
                size="sm"
                @click="goToPage(currentPage + 1)"
              >
                下一页
                <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
              </Button>
            </nav>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white/80 backdrop-blur-sm border-t border-white/20 mt-12">
      <div class="container mx-auto px-4 py-8">
        <div class="text-center">
          <div class="inline-flex items-center justify-center w-12 h-12 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-full mb-4 shadow-lg">
            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
            </svg>
          </div>
          <p class="text-gray-600 text-sm">© 2023 算法题库. 保留所有权利.</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useQuestionStore } from '@/stores/question'
import { questionApi } from '@/api/question'
import { userApi } from '@/api/user'
import { announcementApi } from '@/api/announcement'
import BarrageSystem from '@/components/Common/BarrageSystem.vue'
import DailyQuestionSection from '@/components/Common/DailyQuestionSection.vue'
import Button from '@/components/ui/Button.vue'
import LoadingSpinner from '@/components/ui/LoadingSpinner.vue'
import ErrorState from '@/components/feedback/ErrorState.vue'
import SearchForm from '@/components/forms/SearchForm.vue'
import StatsCard from '@/components/business/StatsCard.vue'
import QuestionCard from '@/components/business/QuestionCard.vue'

const router = useRouter()
const questionStore = useQuestionStore()


// 搜索筛选数据
const searchFilters = ref({
  search: '',
  difficulty: '',
  tag: '',
  status: '',
  favorite: false
})

// 题库弹幕数据
const questionBarrageData = [
  // 统计信息
  { type: 'stats' as const, text: '总题数', value: 'total', color: 'blue' },
  { type: 'stats' as const, text: '已解决', value: 'solved', color: 'green' },
  { type: 'stats' as const, text: '通过率', value: 'rate', color: 'purple' },
  { type: 'stats' as const, text: '今日提交', value: 'submissions', color: 'orange' },
  // 算法标签
  { type: 'tag' as const, text: '数组', tag: 'array' },
  { type: 'tag' as const, text: '动态规划', tag: 'dynamic-programming' },
  { type: 'tag' as const, text: '图', tag: 'graph' },
  { type: 'tag' as const, text: 'BFS', tag: 'breadth-first-search' },
  { type: 'tag' as const, text: 'DFS', tag: 'depth-first-search' },
  { type: 'tag' as const, text: '树', tag: 'tree' },
  { type: 'tag' as const, text: '字符串', tag: 'string' },
  { type: 'tag' as const, text: '哈希表', tag: 'hash-table' },
  { type: 'tag' as const, text: '链表', tag: 'linked-list' },
  { type: 'tag' as const, text: '二分查找', tag: 'binary-search' },
  { type: 'tag' as const, text: '排序', tag: 'sorting' },
  { type: 'tag' as const, text: '栈', tag: 'stack' },
  { type: 'tag' as const, text: '队列', tag: 'queue' },
  { type: 'tag' as const, text: '贪心', tag: 'greedy' },
  { type: 'tag' as const, text: '回溯', tag: 'backtracking' },
  { type: 'tag' as const, text: '滑动窗口', tag: 'sliding-window' },
  { type: 'tag' as const, text: '双指针', tag: 'two-pointers' },
  { type: 'tag' as const, text: '数学', tag: 'math' },
  { type: 'tag' as const, text: '位运算', tag: 'bit-manipulation' },
  { type: 'tag' as const, text: '递归', tag: 'recursion' },
  { type: 'tag' as const, text: '分治', tag: 'divide-and-conquer' },
  { type: 'tag' as const, text: '字典树', tag: 'trie' },
  { type: 'tag' as const, text: '并查集', tag: 'union-find' }
]

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(10)

// 题目数据从API获取
const questions = ref<any[]>([])
const loading = ref(false)
const error = ref('')

// 统计数据
const questionStats = ref({
  total_questions: 0,
  difficulty_stats: {
    easy: 0,
    medium: 0,
    hard: 0
  },
  popular_questions: 0
})

const userStats = ref({
  solved_count: 0,
  total_submissions: 0,
  accepted_submissions: 0,
  acceptance_rate: 0,
  consecutive_days: 0,
  difficulty_stats: {
    easy_solved: 0,
    medium_solved: 0,
    hard_solved: 0
  }
})

// 公告相关
const announcements = ref<any[]>([])
const announcementsLoading = ref(false)
const announcementsError = ref('')
const showAllAnnouncements = ref(false)

// 图标组件
const DocumentIcon = {
  template: `
    <svg class="h-3 w-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>
    </svg>
  `
}

const CheckIcon = {
  template: `
    <svg class="h-3 w-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
    </svg>
  `
}

const ClockIcon = {
  template: `
    <svg class="h-3 w-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
    </svg>
  `
}

const ShieldIcon = {
  template: `
    <svg class="h-3 w-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
    </svg>
  `
}

// 初始化数据
onMounted(async () => {
  await loadQuestions()
  await loadStats()
  await loadAnnouncementsSidebar()
})

onUnmounted(() => {
  // 弹幕系统由BarrageSystem组件自动管理
})

// 统计数据计算属性
const statsData = computed(() => ({
  total: questionStats.value.total_questions,
  solved: userStats.value?.solved_count || 0,
  rate: userStats.value?.acceptance_rate || 0,
  submissions: userStats.value?.total_submissions || 0
}))

// 处理弹幕标签点击
const handleTagClick = (tag: string) => {
  searchFilters.value.tag = tag
  handleFilter()
}

// 加载统计数据
const loadStats = async () => {
  try {
    // 加载题目统计
    const questionStatsResponse = await questionApi.getGlobalQuestionStats()
    if (questionStatsResponse.data) {
      questionStats.value = questionStatsResponse.data
    }
    
    // 加载用户统计（如果用户已登录）
    try {
      const userStatsResponse = await userApi.getCurrentUserStats()
      if (userStatsResponse.data) {
        userStats.value = userStatsResponse.data
      }
    } catch (error) {
      // 用户未登录，使用默认值
      console.log('用户未登录，使用默认统计数据')
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载题目数据
const loadQuestions = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const success = await questionStore.fetchQuestions({
      page: currentPage.value,
      page_size: pageSize.value,
      difficulty: searchFilters.value.difficulty ? [searchFilters.value.difficulty] : [],
      tags: searchFilters.value.tag ? [searchFilters.value.tag] : [],
      status: searchFilters.value.status ? [searchFilters.value.status] : [],
      search: searchFilters.value.search
    })
    
    if (success) {
      questions.value = questionStore.questions || []
    } else {
      error.value = '获取题目失败，请稍后重试'
    }
  } catch (err) {
    console.error('获取题目失败:', err)
    error.value = '网络错误，请检查网络连接'
  } finally {
    loading.value = false
  }
}

// 筛选逻辑 - 现在数据来自API，直接使用store中的数据
const filteredQuestions = computed(() => {
  if (!questions.value) return []
  if (searchFilters.value.favorite) {
    return questions.value.filter(q => q.is_favorited)
  }
  return questions.value
})

// 分页计算 - 使用API返回的分页信息
const totalQuestions = computed(() => questionStore.pagination?.total || 0)
const totalPages = computed(() => questionStore.pagination?.total_pages || 0)

// 可见页码计算
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5 // 最多显示5个页码
  let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const end = Math.min(totalPages.value, start + maxVisible - 1)
  
  // 调整起始页，确保显示足够的页码
  start = Math.max(1, end - maxVisible + 1)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
  loadQuestions()
}

const handleFilter = () => {
  currentPage.value = 1
  loadQuestions()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadQuestions()
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

const handleFavorite = async (id: number) => {
  const question = questions.value?.find(q => q.id === id)
  if (!question) return
  
  try {
    await questionStore.favoriteQuestion(id)
    question.is_favorited = true
    // 同步拉取收藏列表，确保 Favorites.vue 与服务端数据对齐
    await questionStore.fetchFavoriteQuestions()
  } catch (error) {
    console.error('收藏操作失败:', error)
  }
}

const handleUnfavorite = async (id: number) => {
  const question = questions.value?.find(q => q.id === id)
  if (!question) return
  
  try {
    await questionStore.unfavoriteQuestion(id)
    question.is_favorited = false
    // 同步拉取收藏列表，确保 Favorites.vue 与服务端数据对齐
    await questionStore.fetchFavoriteQuestions()
  } catch (error) {
    console.error('取消收藏操作失败:', error)
  }
}

const goToRandomQuestion = async () => {
  if (!questions.value || questions.value.length === 0) {
    await loadQuestions()
  }
  const list = questions.value
  if (list && list.length) {
    const random = list[Math.floor(Math.random() * list.length)]
    router.push(`/questions/${random.id}`)
  }
}

const continueLastPractice = () => {
  const lastId = Number(localStorage.getItem('lastQuestionId'))
  if (lastId) {
    router.push(`/questions/${lastId}`)
  } else if (questions.value && questions.value.length) {
    router.push(`/questions/${questions.value[0].id}`)
  } else {
    router.push('/questions')
  }
}

const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

const loadAnnouncementsSidebar = async () => {
  announcementsLoading.value = true
  announcementsError.value = ''
  try {
    const response = await announcementApi.getAnnouncements({ page: 1, page_size: 5, active: true })
    const list = (response as any)?.data?.announcements || (response as any)?.announcements || []
    announcements.value = Array.isArray(list) ? list : []
  } catch (error: any) {
    console.error('侧栏公告加载失败:', error)
    announcementsError.value = error?.message || '加载公告失败'
    announcements.value = []
  } finally {
    announcementsLoading.value = false
  }
}
</script>